﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Linq;
using System.Linq;
using System.Dynamic;

/// <summary>
/// Summary description for ClassName
/// </summary>
public class Jobamatic
{
    //http://api.simplyhired.com/a/jobs-api/xml-v2/q-c%23+OR+ASP.Net+OR+TDD?pshid=24567&ssty=2&cflg=r&jbd=adnug.jobamatic.com&clip=76.250.82.187
    public static IEnumerable<dynamic> Get(string query){
        try{
        var url ="//http://api.simplyhired.com/a/jobs-api/xml-v2/q-" + query + "?pshid=24567&ssty=2&cflg=r&jbd=adnug.jobamatic.com&clip=76.250.82.187";
            url="http://api.simplyhired.com/a/jobs-api/xml-v2/q-c%23+OR+ASP.Net+OR+TDD?pshid=24567&ssty=2&cflg=r&jbd=adnug.jobamatic.com&clip=76.250.82.187";
        var wc = new System.Net.WebClient();
            //var xml = System.Xml.XmlReader.Create(url);
                /*
       
        var xml = wc.DownloadString(url);
        var doc = new System.Xml.XmlDocument();
            doc.LoadXml(xml);
        var jobs = doc.SelectNodes("//r");
        return jobs.Cast<System.Xml.XmlNode>().Select(n => {
            dynamic d = new ExpandoObject();
            return d;
        
        }).ToArray();*/
        
        using(var stream = wc.OpenRead(url))
            {            
                var settings = new System.Xml.XmlReaderSettings();
                settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                var reader = System.Xml.XmlTextReader.Create(stream,settings);
                
                XDocument xmlDoc = XDocument.Load(reader);
                
                return ((IEnumerable<dynamic>)xmlDoc.Descendants("r").Select(c=> {
                            dynamic d = new ExpandoObject();
                            d.Title = c.Element("jt").Value;
                            d.Description = c.Element("e").Value;
                            d.Url = c.Element("src").Attributes().FirstOrDefault().Value;
                    //.Attributes.Item["url"].Value;
                            //d.Description = c.Element("e");
                            return d;
                        })).ToArray();
            }
            
        }
        catch(Exception e)
        {
            throw new Exception("Could not download jobs " + query,e);
        }
    }
}